package com.aggron.controller;


import com.aggron.bean.PageQuery;
import com.aggron.common.JsonData;
import com.aggron.entity.SysUser;
import com.aggron.params.RoleParams;
import com.aggron.service.ISysRoleService;
import com.aggron.service.ISysRoleUserService;
import com.aggron.service.ISysUserService;
import com.aggron.service.SysTreeService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liuhuan
 * @since 2018-06-02
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController {

    @Autowired
    private ISysRoleService iSysRoleService;

    @Autowired
    private SysTreeService sysTreeService;

    @Autowired
    private ISysRoleUserService iSysRoleUserService;

    @Autowired
    private ISysUserService iSysUserService;

    @GetMapping("/getRoles")
    public Object getUsers(PageQuery pageQuery, RoleParams roleParams){

        return JsonData.success(iSysRoleService.pageRole(pageQuery,roleParams));
    }

    @PostMapping("/save")
    public JsonData save(@RequestBody RoleParams roleParams){
        iSysRoleService.save(roleParams);
        return JsonData.success();
    }

    @PostMapping("/update")
    public JsonData update(@RequestBody RoleParams roleParams){
        iSysRoleService.update(roleParams);
        return JsonData.success();
    }

    /**
     * 角色id
     * @param roleId
     * @return
     */
    @GetMapping("roleTree")
    public JsonData roleTree(Integer roleId){
        return JsonData.success(sysTreeService.roleTree(roleId));
    }

    /**
     * 通过角色id获取用户
     * @param roleId
     * @return
     */
    @GetMapping("users")
    public JsonData users(Integer roleId){
        List<SysUser> selectUserList=iSysRoleUserService.getUserIdByRoleId(roleId);
        List<SysUser> allUserList=iSysUserService.selectList(null);
        List<SysUser> unselectUserList= Lists.newArrayList();
        Set<Integer> userIdSet=selectUserList.stream().map(sysUser -> sysUser.getId()).collect(Collectors.toSet());
        for (SysUser sysUser:allUserList) {
            if(sysUser.getStatus()==1&&!userIdSet.contains(sysUser.getId())){
                unselectUserList.add(sysUser);
            }
        }
        Map<String,List<SysUser>> map= Maps.newHashMap();
        map.put("select",selectUserList);
        map.put("unselect",unselectUserList);
        return JsonData.success(map);
    }



}

